package com.restaurantonlineorder.utils;

import cn.hutool.core.date.DateUtil;
import com.restaurantonlineorder.constant.JWTPropertyKeyConst;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.SneakyThrows;

import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author 熊宇
 * @date 2022/7/20 13:52
 * @description jwt工具类
 */

public class JwtUtil {

    public static final String path = "jwtinfo.properties";

    /**
     * 生成token
     *
     * @param phone
     * @return
     */
    public static String generateToken(String phone, String role) {
        Properties jwtInfo = jwtInfo();
        //密钥
        String secret = jwtInfo.getProperty(JWTPropertyKeyConst.SECRETKEY);

        String expireInfo = jwtInfo.getProperty(JWTPropertyKeyConst.EXPIREKEY);
        //过期时间
        int expire = Integer.parseInt(expireInfo);

        Map map = new HashMap(2);
        map.put("role", role);
        return Jwts.builder()
                .setClaims(map)
                .setSubject(phone)
                .setIssuedAt(new Date())
                .setExpiration(DateUtil.offsetMinute(new Date(), expire))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    /**
     * 获取密钥和token过期时间
     *
     * @return
     */
    @SneakyThrows
    public static Properties jwtInfo() {
        ClassLoader classLoader = JwtUtil.class.getClassLoader();
        InputStream resourceAsStream = classLoader.getResourceAsStream(path);
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        return properties;
    }


    /**
     * 解析token
     *
     * @param jwt
     * @return
     */
    public static Claims parseToken(String jwt) {

        Properties jwtInfo = jwtInfo();
        //密钥
        String secret = jwtInfo.getProperty(JWTPropertyKeyConst.SECRETKEY);

        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(jwt)
                .getBody();

    }
}
